package ca.unbc.cpsc672;

import java.io.IOException;
import java.util.Map;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;

import ca.unbc.cpsc672.fuzzy.IOUtils;
import ca.unbc.cpsc672.fuzzy.RuleSet;
import ca.unbc.cpsc672.fuzzy.rule.FuzzyOperator;

public class FuzzyRuleDialog extends Dialog {
	private Map<String, RuleSet> rulesMap;
	private Button btn1;

	public FuzzyRuleDialog(Shell parentShell) throws IOException {
		super(parentShell);
		rulesMap = IOUtils.loadRuls();
	}

	@Override
	protected Control createContents(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		composite.setLayout(new GridLayout());
		composite.setLayoutData(GUIUtils.buildGridData());

		buildRadioGroup(composite);
		buildTabFolder(composite);
		return super.createContents(parent);
	}

	private void buildRadioGroup(Composite composite) {
		Composite composite2 = new Composite(composite, SWT.NONE);
		composite2.setLayout(new GridLayout(3, false));
		composite2.setLayoutData(GUIUtils.buildGridData());

		Label label = new Label(composite2, SWT.NULL);
		label.setText("Fuzzy Operators: ");

		btn1 = new Button(composite2, SWT.RADIO);
		btn1.setText("Max-min Rules");

		Button btn2 = new Button(composite2, SWT.RADIO);
		btn2.setText("Product Rules");
		btn2.setSelection(!FuzzyOperator.useMinMaxRule);
	}

	private void buildTabFolder(final Composite composite) {
		final CTabFolder cf = new CTabFolder(composite, SWT.NONE);
		cf.setLayoutData(GUIUtils.buildGridData());
		for (String name : rulesMap.keySet()) {
			CTabItem ti = new CTabItem(cf, SWT.NONE);
			ti.setText(name);
			FuzzyRuleTab tab = new FuzzyRuleTab(rulesMap.get(name));
			ti.setControl(tab.createContents(cf));
		}
		cf.setSelection(0);
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("Modify Fuzzy Rules");
	}

	@Override
	protected void okPressed() {
		try {
			FuzzyOperator.useMinMaxRule = btn1.getSelection();
			IOUtils.saveRules(rulesMap.values());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.okPressed();
	}
}